/*global $Client*/
import React, { useState, useEffect, useCallback } from "react";
import { Spin, Table, message, Input, Button } from "antd";
import { getCrmRecordFromSqlAllDataByIn, getCrmRecordFromSql } from "../../util/util"; // 假设这是用于执行 SQL 查询的函数

const columns = [
  {
    title: "商品编码",
    dataIndex: "Product",
    fixed: 'left',
    width: 150, // 设置固定宽度，单位为像素
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "客户货号",
    dataIndex: "AccountprtNo",
    fixed: 'left',
    width: 120, // 设置固定宽度，单位为像素
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "内部货号",
    dataIndex: "internalcode",
    fixed: 'left',
    width: 120, // 设置固定宽度，单位为像素 
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "英文品名",
    fixed: 'left',
    dataIndex: "Englishname",
    width: 220,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "英文规格",
    dataIndex: "Specification",
    width: 180,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "报价项目名称",
    dataIndex: "Quotationitemname",
    width: 150,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "报价日期",
    dataIndex: "Dateofinvoice",
    width: 120,
  },
  {
    title: "汇率",
    dataIndex: "ExchangeRate",
    width: 80,
  },
  {
    title: "品牌",
    dataIndex: "Brand",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "利润倒算",
    dataIndex: "ProfitInversion",
    width: 120,
  },
  {
    title: "起订量",
    dataIndex: "Minimumorder",
    width: 120,
  },
  {
    title: "单位",
    dataIndex: "Unit",
    width: 120,
  },
  {
    title: "USD最终报价",
    dataIndex: "USD_Finalquotation",
    width: 120,
  },
  {
    title: "USD外销公斤价",
    dataIndex: "USD_Exportkilogramprice",
    width: 120,
  },
  {
    title: "商品库外销价格G",
    dataIndex: "Exportprice",
    width: 150,
  },
  {
    title: "利润",
    dataIndex: "Profit",
    width: 120,
  },
  {
    title: "成本费",
    dataIndex: "Costfee",
    width: 120,
  },
  {
    title: "加工费",
    dataIndex: "Processingfee",
    width: 120,
  },
  {
    title: "杀菌费",
    dataIndex: "Sterilizationfee",
    width: 120,
  },
  {
    title: "包装费",
    dataIndex: "Packagingfee",
    width: 120,
  },
  {
    title: "小包+",
    dataIndex: "Smallpackage",
    width: 120,
  },
  {
    title: "大包+",
    dataIndex: "Bigbag",
    width: 120,
  },
  {
    title: "纸箱",
    dataIndex: "Carton",
    width: 120,
  },
  {
    title: "RMB光板",
    dataIndex: "RMB_Opticalplate",
    width: 120,
  },
  {
    title: "入数",
    dataIndex: "Nuofboxesinpg",
    width: 120,
  },
  {
    title: "内盒数",
    dataIndex: "Nuofboxeinnerbox",
    width: 120,
  },
  {
    title: "单净重(G)",
    dataIndex: "Netweightofinnebox",
    width: 120,
  },
  {
    title: "每箱数量",
    dataIndex: "Quantityperbox",
    width: 120,
  },
  {
    title: "长CM",
    dataIndex: "Lengthofouterbox",
    width: 120,
  },
  {
    title: "宽CM",
    dataIndex: "Carton",
    width: 120,
  },
  {
    title: "高CM",
    dataIndex: "Heightofouterbox",
    width: 120,
  },
  {
    title: "体积CBM",
    dataIndex: "Volume",
    width: 120,
  },
  {
    title: "毛重(KG)",
    dataIndex: "Grossweight",
    width: 120,
  },
  {
    title: "净重(KG)",
    dataIndex: "Netweight",
    width: 120,
  },
  {
    title: "包装单位",
    dataIndex: "Packaginunit",
    width: 120,
  },
  {
    title: "包装包数",
    dataIndex: "PackagesNumber",
    width: 120,
  },
  {
    title: "Former Price",
    dataIndex: "former_price",
    width: 120,
  },
  {
    title: "保质期",
    dataIndex: "Shelflife",
    width: 120,
  },
  {
    title: "HSCode",
    dataIndex: "HSCode",
    width: 120,
  },
  {
    title: "中文品名",
    dataIndex: "Productname",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "商品备注",
    dataIndex: "Remarks",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "中文生产要求(材质)",
    dataIndex: "Chptrequirements_material",
    width: 220,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "中文包装描述",
    dataIndex: "ChinesePackagedesp",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "中文成份",
    dataIndex: "Chineseingredients",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  },
  {
    title: "中文规格",
    dataIndex: "Chinesespecification",
    width: 120,
    ellipsis: true, // 截断文本
    style: {
      whiteSpace: 'nowrap', // 禁用文本换行
      textOverflow: 'ellipsis', // 使用省略号
      overflow: 'hidden', // 隐藏溢出部分
    },
  }
];
const feilds = 'id,Parent_Id.ExchangeRate as ExchangeRate,Parent_Id.Dateofinvoice as Dateofinvoice,Parent_Id.Quotationitemname as Quotationitemname,AccountprtNo,internalcode,Englishname,Specification,Brand,ProfitInversion,Minimumorder,Unit,USD_Finalquotation,USD_Exportkilogramprice,Exportprice,Profit,Costfee,Processingfee,Sterilizationfee,Packagingfee,Smallpackage,Bigbag,Carton,RMB_Opticalplate,Nuofboxesinpg,Nuofboxeinnerbox,Netweightofinnebox,Quantityperbox,Lengthofouterbox,Heightofouterbox,Volume,Grossweight,Netweight,Packaginunit,PackagesNumber,former_price,Product,Product.Product_Name as pname,Shelflife,HSCode,Productname,Remarks,Chptrequirements_material,ChinesePackagedesp,Chineseingredients,Chinesespecification';

const App = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [searchText, setSearchText] = useState("");



  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const PDetails = window.wdata?.data?.Quotation_PDetails;
      // console.log(PDetails);
      const accountprtNos = PDetails.map((item) => item.AccountprtNo)
        .filter((item) => item !== null) 
        .filter((item, index, self) => self.indexOf(item) === index); 
      const sql = `select ${feilds} from Quotation_PDetails where id is not null and AccountprtNo `;
      const result = await getCrmRecordFromSqlAllDataByIn(sql, accountprtNos);
      // console.log("result", result);

      setData(result);

    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      fetchData();
    };
    initialize();
  }, [fetchData]);


  const handleSearch = async () => {
    setLoading(true);

    // 在这里处理搜索逻辑，可以根据 searchText 进行筛选或者重新获取数据
    // console.log("Performing search with text:", searchText); 
    var userinfo = await window.ZOHO.CRM.CONFIG.getCurrentUser();
    var userid = userinfo?.users[0].id;
    // console.log('userinfo', userinfo);
    try {
      const sql = `select ${feilds} from Quotation_PDetails where Owner = ${userid} and (((Product.Product_Name like '%${searchText}%' or AccountprtNo like '%${searchText}%') or internalcode like '%${searchText}%') or Englishname like '%${searchText}%') `;
      const result = await getCrmRecordFromSql(sql);
      // console.log("result", result);

      setData(result);
    } catch (e) {
      messageApi(e);
    } finally {
      setLoading(false);

    }

  };
  const handleCopyToQuotation = async () => {
    $Client.close({ "selectedRows": selectedRows});
  };
  const cancel = () => {
    $Client.close();
  };
  //重置，初始化
  const handleReset = () => {
    setSearchText(""); // 清空搜索文本框
    fetchData(); // 重新获取所有数据
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows); // 设置选中的完整数据
    },
  };
  return (
    <div style={{ margin: '8px' }}>
      {contextHolder}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <Input
            placeholder="可按照客户货号、内部货号、英文品名关键字进行搜索"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 400, marginRight: 16 }}
          />
          <Button type="primary" onClick={handleSearch} style={{ marginRight: 16 }}>
            搜索
          </Button>
          <Button onClick={handleReset}>
            初始化查询条件
          </Button>
        </div>
        <div>
          <Button onClick={cancel} style={{ marginRight: 16 }}>
            取消
          </Button>
          <Button onClick={handleCopyToQuotation}>
            添加到本次报价
          </Button>

        </div>
      </div>
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={data}
          scroll={{ x: 5000 }}
          size="small"
          rowKey="id"
          rowSelection={rowSelection}
        />
      </Spin>
    </div>
  );
};
export default App;
